<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        loading-text="加载中..."
        @load="onLoad"
        :immediate-check="false"
        offset="50"
      >
        <ArticleItem
          v-for="item in list"
          :key="item.art_id"
          :artItem="item"
          @dislike="dislikeFn"
          @report="reportFn"
          @click.native="itemClickFn(item.art_id)"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem'
import { getAllArticleListAPI, dislikeArticleAPI, reportArticleAPI } from '@/api/index'
import Notify from '@/ui/Notify'

export default {
  props: {
    channelId: Number // 频道ID
  },
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  data () {
    return {
      list: [], // 文章列表数据
      loading: false, // 底部加载状态
      finished: false, // 底部完成状态
      isLoading: false, // 顶部刷新状态
      theTime: new Date().getTime() // 用于分页
    }
  },
  created () {
    this.getArticleListFn()
  },
  methods: {
    // 专门负责发送请求
    async getArticleListFn () {
      const res = await getAllArticleListAPI({
        channel_id: this.channelId,
        timestamp: this.theTime
      })
      // console.log(res);
      this.list = [...this.list, ...res.data.data.results]
      this.theTime = res.data.data.pre_timestamp
      // 如果不关闭,底部一直是加载中状态,下次触底会再触发onLoad
      this.loading = false
      // 代表本次回来的数据是最后的，没有下一段数据了
      if (res.data.data.pre_timestamp === null) {
        this.finished = true
      }

      // 顶部加载状态改为false
      this.isLoading = false
    },
    // 底部加载事件方法
    onLoad () {
      if (this.list.length === 0) {
        return // 如果页面没有数据,不往下执行
      }
      this.getArticleListFn()
    },
    // 顶部刷新数据方法
    onRefresh () {
      this.list = []
      this.theTime = new Date().getTime()
      this.getArticleListFn()
    },
    // 反馈(不感兴趣)
    async dislikeFn (id) {
      try {
        await dislikeArticleAPI({
          artId: id
        })
        Notify({ type: 'success', message: '反馈成功' })
      } catch (err) {
      }
    },
    // 反馈垃圾内容-举报文章
    async reportFn (id, value) {
      await reportArticleAPI({
        artId: id,
        type: value
      })
      Notify({ type: 'success', message: '举报成功' })
    },
    // 跳转到详情
    itemClickFn (id) {
      this.$router.push({
        path: `/detail?art_id=${id}`
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
